package com.giraffe.device.strategy;

import com.alibaba.fastjson2.JSONObject;
import com.giraffe.device.config.TdEngineConfig;
import com.giraffe.device.pojo.dto.TuYaTemperatureDTO;
import com.giraffe.device.pojo.enums.DeviceTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author ldx
 * @Date 2024/02/21 18:30
 **/
@Slf4j
@Component
public class DeviceMessageParsingForTuYaTemperatureStrategy implements SecondaryDeviceMessageParsingStrategy {

    @Resource
    private TdEngineConfig tdEngineConfig;

    @Override
    public String deviceTypeCode() {
        return DeviceTypeEnum.TUYA_TEMPERATURE.getCode();
    }

    @Override
    public void parsing(String deviceId,String message) {
        log.info("解析设备消息：{}，设备ID：{}",message,deviceId);
        TuYaTemperatureDTO dto = JSONObject.parseObject(message,TuYaTemperatureDTO.class);

        try {
            String sql = "INSERT INTO tb_"+deviceId+" USING temperature TAGS('13541033908')" +
                    " VALUES(NOW(),"+dto.getTemperature()+","+dto.getHumidity()+","+dto.getLinkQuality()+","+dto.getBatteryPercentage()+","+dto.getBatteryVoltage()+")";
            System.out.println(sql);
            Statement stmt = tdEngineConfig.tdEngine();
            if(dto.getTemperature() == 0){
                String lastTemperatureSql = "select temperature from giraffe.tb_"+deviceId+" where temperature > 0 order by ts desc limit 1";
                ResultSet resultSet = stmt.executeQuery(lastTemperatureSql);
                double temperature = 0;
                while (resultSet.next()) {
                    temperature = resultSet.getDouble("temperature");
                }
                dto.setTemperature(temperature);
            }
            if(dto.getHumidity() == 0){
                String lastHumiditySql = "select humidity  from giraffe.tb_"+deviceId+" where humidity > 0 order by ts desc limit 1";
                ResultSet resultSet = stmt.executeQuery(lastHumiditySql);
                double humidity = 0;
                while (resultSet.next()) {
                    humidity = resultSet.getDouble("humidity");
                }
                dto.setHumidity(humidity);
            }
            stmt.executeUpdate("INSERT INTO tb_"+deviceId+" USING temperature TAGS('13541033908')" +
                    " VALUES(NOW(),"+dto.getTemperature()+","+dto.getHumidity()+","+dto.getLinkQuality()+","+dto.getBatteryPercentage()+","+dto.getBatteryVoltage()+")");
            tdEngineConfig.tdEngineClose(stmt);
        }catch (SQLException e){
            log.error("xxx",e);
        }

    }

}
